package net.oschina.dajiangnan.tree;

import java.util.Map;

public class TreeExecute {
    private TreeExecute() {
    }

    private static class SingletonFactory {
        private static TreeExecute instance = new TreeExecute();
    }

    public static TreeExecute me() {
        return SingletonFactory.instance;
    }


    public Node execute(AbstractContext context, Node rootNode) {
        Node node = rootNode;
        do {
            Node nextNode = node.process(context);
            if (nextNode == null) {
                return node;
            }
            node = nextNode;
        } while (true);
    }

    public HandlerResult execute(AbstractContext context, Node rootNode,
                                 Map<Class, ? extends BaseNodeHandler> handlerMap) {
        Node node = rootNode;
        do {
            Node nextNode = node.process(context);
            if (nextNode == null) {
                break;
            }
            node = nextNode;
        } while (true);
        if (handlerMap == null || !handlerMap.containsKey(node.getClass())) {
            return null;
        }
        return handlerMap.get(node.getClass()).handle(context, (AbstractNode) node);
    }
}